package com.trt.contentcenter;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.sun.deploy.security.BlockedException;
import com.trt.contentcenter.dao.content.ShareMapper;
import com.trt.contentcenter.domain.dto.user.UserDTO;
import com.trt.contentcenter.domain.entity.content.Share;
import com.trt.contentcenter.feignclient.TestBaiduFeignClient;
import com.trt.contentcenter.feignclient.TestUserCenterFeignClient;
import com.trt.contentcenter.sentineltest.TestControllerBlockHandlerClass;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @version 1.0
 * @author: trt
 * @description:
 * @create: 2021-03-21 02:38
 */
@Slf4j
@RestController
@RefreshScope // 配置属性动态刷新
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TestController {

    // @Autowired
    private final ShareMapper shareMapper;

    private final DiscoveryClient discoveryClient;

    @GetMapping("/test")
    public  List<Share> testInsert(){
        Share share = new Share();
        share.setCreateTime(new Date());
        share.setUpdateTime(new Date());
        share.setTitle("xxx");
        share.setCover("xxx");
        share.setAuthor("TRT");
        share.setBuyCount(1);
        this.shareMapper.insertSelective(share);

        List<Share> shares = this.shareMapper.selectAll();

        return shares;
    }

    /**
     * 测试: 服务发现，证明内容中心总能找到服务中心
     * @return 用户中心所有实例的地址信息
     */
    @GetMapping("test2")
    public List<ServiceInstance> getInstance(){
        // 查询指定服务的所有实例信息
        return this.discoveryClient.getInstances("user-center");
    }

    @Autowired
    private TestUserCenterFeignClient testUserCenterFeignClient;

    @GetMapping("test-get")
    public UserDTO query(UserDTO userDTO){
        return testUserCenterFeignClient.query(userDTO);
    }

    @Autowired
    private TestBaiduFeignClient testBaiduFeignClient;

    @GetMapping("baidu")
    public String baiduIndex(){
        return this.testBaiduFeignClient.index();
    }

    @Autowired
    private TestService testService;

    @GetMapping("test-a")
    public String testA(){
        this.testService.common();
        return "test-a";
    }

    @GetMapping("test-b")
    public String testB(){
        this.testService.common();
        return "test-b";
    }

    // 热点规则
    @GetMapping("test-hot")
    @SentinelResource("hot")
    public String testHot(@RequestParam(required = false) String a,
                          @RequestParam(required = false) String b){
        return a + " " + b;
    }

    // 代码配置规则
    @GetMapping("test-add-flow-rule")
    public String testHot(){
        return "success";
    }

    private void initFlowQpsRule() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule("/shares/1");
        // set limit qps to 20
        rule.setCount(20);
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setLimitApp("default");
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

    // Sentinel API详解 SphU:定义资源，监控，保护、Tracer:对异常进行统计、ContextUtil:调用来源
    @GetMapping("/test-sentinel-api")
    public String testSentinelAPI(@RequestParam(required = false) String a){
        String resourceName = "test-sentinel-api";
        ContextUtil.enter(resourceName, "test-wfw");
        // 定义一个sentinel保护的资源,名称是test-sentinel-api
        Entry entry = null;
        try {
            entry = SphU.entry(resourceName);
            // 被保护的业务逻辑
            if (StringUtils.isBlank(a)) {
                throw new IllegalArgumentException("a不能为空");
            }
            return a;
        }
        // 如果被保护的资源被限流或者降级了，就会抛BlockedException
        catch (BlockException e){
            log.warn("限流,或者降级了", e);
            return "限流,或者降级了";
        } catch (IllegalArgumentException e2){
            //统计IllegalArgumentException【发生的次数、发生占比...】
            Tracer.trace(e2);
            return "参数非法!";
        } finally {
            if (entry != null) {
                // 退出entry
                entry.exit();
            }
            ContextUtil.exit();
        }

    }

    @GetMapping("/test-sentinel-resource")
//    @SentinelResource(value = "test-sentinel-api", blockHandler = "block", fallback = "fallback")
    @SentinelResource(value = "test-sentinel-api",
            blockHandler = "block",
            blockHandlerClass = TestControllerBlockHandlerClass.class,
            fallback = "fallback")
    public String testSentinelResource(@RequestParam(required = false) String a){
        // 被保护的业务逻辑
        if (StringUtils.isBlank(a)) {
            throw new IllegalArgumentException("a cannot be blank.");
        }
        return a;
    }

    /**
     * 处理限流或者降级
     * @param a
     * @param e
     * @return
     */
//    public String block(String a, BlockedException e){
//        log.warn("限流,或者降级了 block", e);
//        return "限流,或者降级了 block";
//    }

    /**
     * 1.5 处理降级
     *  - sentinel 1.6 可以处理Throwable
     * @param a
     * @return
     */
    public String fallback(String a){
        return "限流,或者降级了 fallback";
    }


    @Autowired
    private RestTemplate restTemplate;

    // RestTemplate 整合sentinel
    @GetMapping("/test-rest-template-sentinel/{userId}")
    public UserDTO test(@PathVariable Integer userId){
        return this.restTemplate.getForObject("http://user-center/users/{userId}", UserDTO.class, userId);
    }

    @Autowired
    private Source source;

    @GetMapping("/test-stream")
    public String testStream(){
        this.source.output()
                .send(
                        MessageBuilder
                                .withPayload("消息体")
                                .build()
                );
        return "success";
    }

//    @Autowired
//    private MySource mySource;
//
//    @GetMapping("/test-stream-2")
//    public String testStream2(){
//        this.mySource.output()
//                .send(
//                        MessageBuilder
//                                .withPayload("消息体")
//                                .build()
//                );
//        return "success";
//    }





    /**
     *  RestTemplate传递Token
     *  1.exchange()
     *  2.ClientHttpRequestInterceptor
     */
    @GetMapping("/tokenRelay/{userId}")
    public ResponseEntity<UserDTO> tokenRelay(@PathVariable Integer userId, HttpServletRequest request){
//        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
//        ServletRequestAttributes attributes = (ServletRequestAttributes)requestAttributes;
//        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("X-Token");

        HttpHeaders headers = new HttpHeaders();
        headers.add("X-Token", "xxxx");
        return this.restTemplate
                .exchange(
                    "http://user-center/users/{userId}",
                    HttpMethod.GET,
                    new HttpEntity<>(headers),
                    UserDTO.class,
                    userId
                );

    }

    @Value("${your.configuration}")
    public String testConfiguration;

    @GetMapping("/test-config")
    public String testConfiguration(){
        return this.testConfiguration;
    }






}